import validate from "@/utils/validate";


let transferToTreeData = (list,id,parentId,children,rootId) => {
    if(!validate.isArray(list)){
        return list;
    }
    id = id || 'id'
    parentId =  parentId || 'parentId'
    children =  children || 'children'
    rootId =  rootId || 0;
    //对源数据深度克隆
    const cloneData = JSON.parse(JSON.stringify(list))
    //循环所有项
    const treeData = cloneData.filter(father => {
        let branchArr = cloneData.filter(child => {
            //返回每一项的子级数组
            return father[id] === child[parentId]
        });
        if(!validate.isEmptyArray(branchArr)){
            father[children] = branchArr;
        }
        //返回第一层
        return father[parentId] === rootId;
    });
    return validate.isEmptyArray(treeData) ? list : treeData;
}

let transferToRouterData = (list,id,parentId,children,rootId) =>{
    if(!validate.isArray(list)){
        return list;
    }
    id = id || 'id'
    parentId =  parentId || 'parentId'
    children =  children || 'children'
    rootId =  rootId || 0;
    const cloneData = JSON.parse(JSON.stringify(list))
    const treeData = cloneData.filter(father => {
        let branchArr = cloneData.filter(child => {
            return father[id] === child[parentId]
        });
        if(!validate.isEmptyArray(branchArr)){
            father[children] = branchArr;
        }
        return father[parentId] === rootId;
    });
    return validate.isEmptyArray(treeData) ? list : treeData;
}

export default {
    transferToTreeData:transferToTreeData,
    transferToRouterData:transferToRouterData
}